package com.codrim.cs.data.server.utils;

import org.apache.commons.lang3.math.NumberUtils;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.util.Date;

/**
 * Created by Liang.Zhuge on 04/05/2017.
 */
public class DateUtils {
    public static final String YMDHMS = "yyyyMMddHHmmss";
    public static final String YYYY_M_MDD_HH = "yyyyMMddHH";
    public static final String YYYY_MM_DD = "yyyy-MM-dd";

    /**
     * 将`Date`转化为默认时区的指定格式字符串
     *
     * @param date    待格式化时间
     * @param pattern 格式字符串
     * @return 格式化后字符串
     */
    public static String toString(Date date, String pattern) {
        return DateTimeFormatter.ofPattern(pattern)
                .withZone(ZoneId.systemDefault()).format(date.toInstant());
    }

    public static String toString(Date date, String pattern, int zone) {
        return DateTimeFormatter.ofPattern(pattern).withZone(zoneId(zone)).format(date.toInstant());
    }

    /**
     * 将`Date`转化为零时区的指定格式字符串
     *
     * @param date    待格式化时间
     * @param pattern 格式字符串
     * @return 格式化后0时区日期字符串
     */
    public static String toUTCString(Date date, String pattern) {
        return DateTimeFormatter.ofPattern(pattern).withZone(ZoneId.of("UTC")).format(date.toInstant());
    }

    public static String format(Date date, String pattern) {
        return DateFormatUtils.format(date, pattern);
    }

    public static Date parse(String sDate, String pattern, int timeZone) {
        ZoneId of = zoneId(timeZone);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern).withZone(of);
        TemporalAccessor parse = formatter.parse(sDate);
        Date date = new Date();
        date.setTime(Instant.from(parse).toEpochMilli());
        return date;
    }

    public static ZoneId zoneId(int timeZone) {
        if (timeZone > 12 || timeZone < -12) {
            throw new IllegalArgumentException("Time sZone must between -12 and 12");
        }

        String sZone = timeZone >= 0 ? ("UTC+" + timeZone) : ("UTC-" + Math.abs(timeZone));
        return ZoneId.of(sZone);
    }

    public static int dateToInt(Date sdate) {
        return NumberUtils.toInt(DateFormatUtils.format(sdate, "yyyyMMdd"));
    }
}
